from cold_start_analyzer.base_analyzer import BaseAnalyzer
from cold_start_analyzer.consts import NOT_AVAILABLE
from cold_start_analyzer import db_helper
from cold_start_analyzer.log_helper import dlog


class Phase2All(BaseAnalyzer):
    description = "应用进程启动: 从HandleLaunchApplication开始到结束"
    def get_result(self):
        """
        起点： app_thread
        H:void OHOS::AppExecFwk::MainThread::HandleLaunchApplication 开始
        终点： app_thread
        H:void OHOS::AppExecFwk::MainThread::HandleLaunchApplication 结束
        """
        if 'Phase1All' not in self.context:
            return NOT_AVAILABLE
        res = db_helper.get_function_cost(self.cursor, 'H:void OHOS::AppExecFwk::MainThread::HandleLaunchApplication', self.context['Phase1All']['end_ts']-1, None, thread_name=self.thread_name)
        if not res:
            dlog.error(f"query_function_cost failed: {self.thread_name}, res: {res}")
            return NOT_AVAILABLE
        self.context['Phase2All'] = {
            'start_ts': res[0][0],
            'end_ts': res[0][1],
        }
        return res[0][1] - self.context['Phase1All']['end_ts']